package com.buildings.activity.map;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.bigkoo.pickerview.OptionsPickerView;
import com.buildings.R;
import com.buildings.activity.form.NewProjectFormActivity;
import com.buildings.activity.reinforce.HouseReinforceFormActivity;
import com.buildings.api.Api;
import com.buildings.base.BaseActivity;
import com.buildings.bean.BaseBean;
import com.buildings.bean.FormListBean;
import com.buildings.bean.ReinforceListResult;
import com.buildings.bean.ReinforceResult;
import com.buildings.bean.SDBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.MyHttpClient;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.FormDataUtil;
import com.buildings.util.PickViewUtil;
import com.buildings.util.SPUtil;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;

/**
 * @author yiem
 * @packager com.buildings.activity.map
 * @date 2020/9/9
 **/
public class ReinforceFormListActivity extends BaseActivity implements View.OnClickListener {

  public static void intentReinforceFormListActivity(Activity activity, String projectType,
      String status) {
    Intent intent = new Intent();
    intent.setClass(activity, ReinforceFormListActivity.class);
    intent.putExtra("projectType", projectType);
    intent.putExtra("status", status);
    activity.startActivity(intent);
  }

  @BindView(R.id.tv_title) TextView tvTitle;
  @BindView(R.id.iv_back) ImageView ivBack;
  @BindView(R.id.tv_right_text) TextView tvSelect;
  @BindView(R.id.tv_left_text) TextView tvLeftText;
  @BindView(R.id.recyclerView) RecyclerView recyclerView;
  @BindView(R.id.refreshLayout) SmartRefreshLayout refreshLayout;
  @BindView(R.id.tv_status) TextView tvStatus;//表单状态
  @BindView(R.id.tv_sort) TextView tvSort;//排序

  @BindView(R.id.btn_commit) Button btnCommit;
  @BindView(R.id.btn_delete) Button btnDelete;
  @BindView(R.id.ll_bottom) LinearLayout llBottom;//批量提交布局

  private int pageNum = 1;//当前请求页数
  private int pageSize = 15;
  private int total;//
  private Dialog dialog;

  private ReinforceFormListAdapter mAdapter;
  private List<ReinforceResult.ReinforceData> data;

  private String status;
  private String type = "";
  private String buildType = "4";
  private String projectType;
  private String userId;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_form_list);
    ButterKnife.bind(this);
    initData();
    initView();
  }

  private void initData() {
    projectType = getIntent().getStringExtra("projectType");
    status = getIntent().getStringExtra("status");//2已完成，   已完成任务下的表单
    userId = (String) SPUtil.get("userId", "");
  }

  private void initView() {
    tvTitle.setText("表单");
    tvSelect.setText("选择");
    //        tvLeftText.setVisibility(View.VISIBLE);
    tvLeftText.setText("全选");
    refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
      @Override public void onLoadmore(RefreshLayout refreshlayout) {
        if (data.size() >= total) {
          CustomToast.showToast(activity, "没有更多的内容");
          refreshlayout.finishLoadmore();
        } else {
          getFormList(projectType);
        }
      }
    });
    refreshLayout.setOnRefreshListener(new OnRefreshListener() {
      @Override public void onRefresh(RefreshLayout refreshlayout) {
        pageNum = 1;
        getFormList(projectType);
      }
    });

    showAdapter();
  }

  @OnClick({
      R.id.iv_back, R.id.tv_status, R.id.tv_sort, R.id.tv_right_text, R.id.btn_commit,
      R.id.btn_delete, R.id.tv_left_text
  }) public void onClick(View v) {
    switch (v.getId()) {
      case R.id.iv_back:
        finish();
        break;
      case R.id.tv_status:
        final List<String> statusList = FormDataUtil.getFormListStatus();
        PickViewUtil.showPickerViewOne(activity, "表单状态", statusList,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String str = statusList.get(options1);
                // 0未提交  1未审核  2审核未通过 3审核通过   4全部
                if (TextUtils.equals(FormDataUtil.ALL, str)) {
                  type = "";
                } else if (TextUtils.equals(FormDataUtil.NO_COMMIT, str)) {
                  type = "0";
                } else if (TextUtils.equals(FormDataUtil.NO_VERIFY, str)) {
                  type = "1";
                } else if (TextUtils.equals(FormDataUtil.VERIFY_FAILED, str)) {
                  type = "2";
                } else if (TextUtils.equals(FormDataUtil.VERIFY_SUCCESS, str)) {
                  type = "3";
                }
                tvStatus.setText(str);
                if (dialog != null && !dialog.isShowing()) {
                  dialog.show();
                }
                setEditStatus(true);
                pageNum = 1;
                getFormList(projectType);
              }
            });
        break;
      case R.id.tv_sort:
        final List<String> sortList = FormDataUtil.getRFormListSort();
        PickViewUtil.showPickerViewOne(activity, "建筑类型", sortList,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String str = sortList.get(options1);
                //0、加固 1 新建
                if (TextUtils.equals(FormDataUtil.ALL, str)) {
                  projectType = "";
                } else if (TextUtils.equals(FormDataUtil.REINFORCE_PROJECT, str)) {
                  projectType = "0";
                } else if (TextUtils.equals(FormDataUtil.NEW_PROJECT, str)) {
                  projectType = "1";
                }
                tvSort.setText(str);
                if (dialog != null && !dialog.isShowing()) {
                  dialog.show();
                }
                setEditStatus(true);
                pageNum = 1;
                getFormList(projectType);
              }
            });
        break;
      case R.id.tv_left_text:
        //全选反选
        if (TextUtils.equals("全选", tvLeftText.getText().toString())) {
          tvLeftText.setText("反选");
          for (ReinforceResult.ReinforceData bean : data) {
            bean.checked = true;
          }
        } else {
          tvLeftText.setText("全选");
          for (ReinforceResult.ReinforceData bean : data) {
            bean.checked = false;
          }
        }
        mAdapter.notifyDataSetChanged();

        break;
      case R.id.tv_right_text:
        setEditStatus(mAdapter.isEdit());
        break;
      case R.id.btn_commit:
        //如果选中的有未完善的提示不能提交
        //                for(ReinforceResult.ReinforceData bean : data){
        //                    if (TextUtils.equals(bean.getIsSaveAll(),"0")){//是否填完0、否  1、是
        //
        //                    }
        //                }
        String ids = "";
        for (ReinforceResult.ReinforceData bean : data) {
          if (bean.checked) {
            if (TextUtils.equals(bean.isSaveAll, "0")) {//是否填完0、否  1、是
              //未完善标红提示
              //                            mAdapter.setCommitTips(true);
              //                            mAdapter.notifyDataSetChanged();
              CustomToast.showToast(activity, "有未填完的表单");
              return;
            }
            ids = ids + bean.id + ",";
          }
        }
        if (!TextUtils.isEmpty(ids)) {
          String str = ids.substring(0, ids.length() - 1);
          ids = str;
        }
        Log.e("ids", "ids = " + ids);
        if (TextUtils.isEmpty(ids)) {
          CustomToast.showToast(activity, "请选择要提交表单");
          return;
        }
        final String finalIds = ids;
        DialogUtils.showIOSDialog(activity, "提示", "", "", "", "", null, new View.OnClickListener() {
          @Override public void onClick(View view) {
            dialog.show();
            updateFormList(finalIds);
          }
        }, "确定要提交选择的表单？");

        break;
      case R.id.btn_delete:
        String deleteIds = "";
        for (ReinforceResult.ReinforceData bean : data) {
          if (bean.checked) {
            deleteIds = deleteIds + bean.id + ",";
          }
        }
        if (!TextUtils.isEmpty(deleteIds)) {
          String str = deleteIds.substring(0, deleteIds.length() - 1);
          deleteIds = str;
        }
        Log.e("ids", "ids = " + deleteIds);
        if (TextUtils.isEmpty(deleteIds)) {
          CustomToast.showToast(activity, "请选择要删除表单");
          return;
        }
        final String finalDeleteIds = deleteIds;
        DialogUtils.showIOSDialog(activity, "提示", "", "", "", "", null, new View.OnClickListener() {
          @Override public void onClick(View view) {
            dialog.show();
            deleteFormList(finalDeleteIds);
          }
        }, "确定要删除选择的表单？");

        break;
    }
  }

  private void setEditStatus(boolean flag) {
    for (ReinforceResult.ReinforceData bean : data) {
      bean.checked = false;
    }
    if (flag) {
      mAdapter.setEdit(false);
      mAdapter.setCommitTips(false);
      tvSelect.setText("选择");
      llBottom.setVisibility(View.GONE);
      tvLeftText.setVisibility(View.GONE);
      refreshLayout.setEnableLoadmore(true);
      refreshLayout.setEnableRefresh(true);
    } else {
      mAdapter.setEdit(true);
      tvSelect.setText("取消");
      mAdapter.setCommitTips(true);
      llBottom.setVisibility(View.VISIBLE);
      tvLeftText.setVisibility(View.VISIBLE);
      tvLeftText.setText("全选");
      refreshLayout.finishLoadmore();
      refreshLayout.finishRefresh();
      refreshLayout.setEnableLoadmore(false);
      refreshLayout.setEnableRefresh(false);
    }
    mAdapter.notifyDataSetChanged();
  }

  private void showAdapter() {
    data = new ArrayList<>();

    //        LinearLayoutManager linerLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(new LinearLayoutManager(activity));
    //        recyclerView.addItemDecoration( new DividerGridItemDecoration(getActivity() ));
    recyclerView.addItemDecoration(
        new DividerItemDecoration(activity, LinearLayoutManager.VERTICAL));
    mAdapter = new ReinforceFormListAdapter(activity, data);
    recyclerView.setAdapter(mAdapter);
    mAdapter.setOnItemClickListener(new ReinforceFormListAdapter.OnItemClickListener() {
      @Override public void onItemClick(View view, int position) {
        if (!mAdapter.isEdit()) {
          ReinforceResult.ReinforceData bean = data.get(position);
          //                    String type = bean.getSpType();//表单状态  0未提交  1未审核  2审核未通过 3审核通过
          //                    if(TextUtils.equals("0",type)){
          startForm(position, bean);
          //                    }
        }
      }

      @Override public void onItemLongClick(View view, final int position) {

      }

      @Override public void onSubmit(View view, int position) {
        final ReinforceResult.ReinforceData bean = data.get(position);
        DialogUtils.showIOSDialog(activity, "提示", "", "", "", "", null, new View.OnClickListener() {
          @Override public void onClick(View view) {
            dialog.show();
            updateFormList(bean.id);
          }
        }, "确定要提交当前表单？");
      }

      @Override public void onEdit(View view, int position) {
        ReinforceResult.ReinforceData bean = data.get(position);
        startForm(position, bean);
      }

      @Override public void onDelete(View view, final int position) {
        DialogUtils.showIOSDialog(activity, "提示", "", "", "", "", null, new View.OnClickListener() {
          @Override public void onClick(View view) {
            ReinforceResult.ReinforceData bean = data.get(position);
            dialog.show();
            deleteFormList(bean.id);
          }
        }, "确定要删除该表单？");
      }
    });
    dialog = DialogUtils.showRefreshDialog(activity);
    getFormList(projectType);

    if (TextUtils.equals("2", status)) {
      tvSelect.setVisibility(View.INVISIBLE);
      mAdapter.setStatus(status);
    }
  }

  private void startForm(int position, ReinforceResult.ReinforceData bean) {
    //0、城镇住宅1、城镇非住宅，2、农村住房，3、农村公共住宅
    if (bean == null) {
      return;
    }

    if (bean.projectType.equals("0")) {
      HouseReinforceFormActivity.intentHouseReinforceFormActivity(this, bean, "");
    } else {
      NewProjectFormActivity.intentNewProjectFormActivity(this, bean, "");
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1000 && resultCode == RESULT_OK) {
      setEditStatus(true);
      pageNum = 1;
      dialog.show();
      getFormList(projectType);
    }
  }

  private void update() {
    mAdapter.update(data);
  }

  private void getFormList(String projectType) {
    if (projectType == null) {
      projectType = "";
    }
    String url = Api.REINFORCE
        + "page?projectType="
        + projectType
        + "&status="
        + type
        + "&curPage="
        + pageNum
        + "&pageSize="
        + pageSize;

    MyHttpClient.newBuilder().get().url(url)
        //                .addParam(jsonBuilder.toJsonString())
        .build().enqueue(new BaseCallBack<ReinforceListResult>() {
      @Override public void onSuccess(ReinforceListResult bean) {
        super.onSuccess(bean);
        refreshLayout.finishLoadmore();
        refreshLayout.finishRefresh();
        if (bean.getCode() == 200) {
          if (pageNum == 1) {
            //第一页
            data.clear();
          }
          pageNum++;
          total = bean.data.total;
          List<ReinforceResult.ReinforceData> result = bean.data.rows;
          data.addAll(result);
          update();
        } else {
          CustomToast.showToast(activity, "获取失败");
        }
        if (dialog != null) {
          dialog.dismiss();
        }
      }

      @Override public void onFailure(Call call, IOException e) {
        super.onFailure(call, e);
        refreshLayout.finishLoadmore();
        refreshLayout.finishRefresh();
        CustomToast.showToast(activity, "网络异常");
        if (dialog != null) {
          dialog.dismiss();
        }
      }

      @Override public void onError(int code) {
        super.onError(code);
        refreshLayout.finishLoadmore();
        refreshLayout.finishRefresh();
        CustomToast.showToast(activity, "网络异常");
        if (dialog != null) {
          dialog.dismiss();
        }
      }
    });
  }

  /**
   * 批量提交表单   {type}/subAll/{ids}
   */
  private void updateFormList(String ids) {
    String url = Api.REINFORCE + "submit/"+ids;

    if (TextUtils.isEmpty(ids)){
      return;
    }
    SDBean sdBean = new SDBean();
    sdBean.ids = ids;
    MyHttpClient.newBuilder()
        .post()
        .url(url)
        .build()
        .enqueue(new BaseCallBack<BaseBean>() {
          @Override public void onSuccess(BaseBean bean) {
            super.onSuccess(bean);
            if (bean != null && bean.getCode() == 200) {
              setEditStatus(true);
              pageNum = 1;
              getFormList(projectType);
            } else {
              CustomToast.showToast(activity, "提交失败");
            }
            if (dialog != null) {
              dialog.dismiss();
            }
          }

          @Override public void onFailure(Call call, IOException e) {
            super.onFailure(call, e);
            CustomToast.showToast(activity, "网络异常");
            if (dialog != null) {
              dialog.dismiss();
            }
          }

          @Override public void onError(int code) {
            super.onError(code);
            CustomToast.showToast(activity, "网络异常");
            if (dialog != null) {
              dialog.dismiss();
            }
          }
        });
  }

  /**
   * 批量删除表单   /{ids}/deletAll
   */
  private void deleteFormList(String ids) {
    String url = Api.REINFORCE + "del/"+ids;

    if (TextUtils.isEmpty(ids)){
      return;
    }
    SDBean sdBean = new SDBean();
    sdBean.ids = ids;
    MyHttpClient.newBuilder()
        .post()
        .url(url)
        .build()
        .enqueue(new BaseCallBack<BaseBean>() {
          @Override public void onSuccess(BaseBean bean) {
            super.onSuccess(bean);
            if (bean != null && bean.getCode() == 200) {
              setEditStatus(true);
              pageNum = 1;
              getFormList(projectType);
            } else {
              CustomToast.showToast(activity, "提交失败");
            }
            if (dialog != null) {
              dialog.dismiss();
            }
          }

          @Override public void onFailure(Call call, IOException e) {
            super.onFailure(call, e);
            CustomToast.showToast(activity, "网络异常");
            if (dialog != null) {
              dialog.dismiss();
            }
          }

          @Override public void onError(int code) {
            super.onError(code);
            CustomToast.showToast(activity, "网络异常");
            if (dialog != null) {
              dialog.dismiss();
            }
          }
        });
  }
}

